<?php
/**
 * 粉丝模块
 */
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\util\WechatThirdUtil;
use app\common\model\WxUser;
use app\common\model\Users as UsersModel;
use think\Db;
use think\Session;
// 公众号数据表
use app\common\model\AuthorWxUser as AuthorWxUserModel;

class Fans extends AdminBase
{
    protected $wechat_obj;
    protected $config;
    protected $author_config;
    protected $wx_user_model;
    protected $users_model;
    protected $author_wx_user_model;
    protected function _initialize(){
        parent::_initialize();
        $this->wx_user_model = new WxUser;
        $this->users_model = new UsersModel;
        $this->config = $this->wx_user_model->find();
        $this->author_config = session::get('wechat_info');
        $this->wechat_obj = new WechatThirdUtil($this->config , $this->author_config);
        $this->author_wx_user_model = new AuthorWxUserModel();
    }

    /*
     * 获取当前公众号下面的粉丝数据
     * */
    public function index(){
        return $this->fetch();
    }

    public function allfans($start_time = '',$end_time = '',$page = 1,$keyword = ''){
        $count = '';
        $where = [];
        if(!empty($start_time) && !empty($end_time)){
            $where = [
                'subscribe_time'=>['between',[$start_time,$end_time]],
            ];
        }
        if (!empty($keyword)) {
            $where['think_users.nickname'] = ['like','%'.$keyword.'%'];
        }
        $where['think_users.auid'] = ['eq',$this->author_config['id']];
        $count = Db::name('users')
            ->field('COUNT(*) total,COUNT(CASE WHEN subscribe = 1 THEN 1 ELSE NULL END) subscount,COUNT(CASE WHEN subscribe = 0 THEN 1 ELSE NULL END ) un_subscount,COUNT(CASE WHEN repeat_subscribe = 1 && subscribe = 1 THEN 1 ELSE NULL END) repeat_subscribe_count,COUNT(CASE WHEN is_second_unsubscribe = 1 THEN 1 ELSE NULL END) as second_unsubscribe_count')
            ->where($where)
            ->select();//关注人数

        $result = $this->users_model
            ->field('u.butt_id,u.user_id,u.auid,u.sex,u.subscribe_time,u.unsubscribe_time,u.subscribe,u.openid,u.headimgurl,u.nickname,think_csuser.nickname as cs_nickname')
            ->alias('u')
            ->join('think_csuser','u.butt_id = think_csuser.id','left')
            ->where($where)
            ->order('subscribe_time desc')
            ->paginate(15,false,['page'=>$page]);

        foreach($result as $v){
            $map = [
                'openid' => ['eq',$v['openid']],
                'cs_id' => ['eq',$v['butt_id']]
            ];
            $v['chat_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->group('send_type')->column('send_type,count(*) as chat_count');
        }

        //统计菜单栏点击数
        $click_count = Db::name('wechat_menu_click')->where('auid',$this->author_config['id'])->count();
       return $this->fetch(
           'allfans',[
               'allfans'=>$result,
                'keyword'=> $keyword
           ]
       );
    }

    /*
     *
     * */
    public function chat(){
        return $this->fetch();
    }

    /**
     * 获取粉丝列表 获取公众号上的粉丝列表
     */
    public function getFansList(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getFanIdList();
        return json($result);
    }

    public function updateFansInfo(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getFanIdList('ovBM91UgMUBxp8pGhu05PPW-rJcg');
        $openids = $result['data']['openid'];

        foreach($openids as $v){
            $wxdata = $wechat_obj->getFanInfo($v);
            $user = [
                'openid'    => $v,
                'auid'      => $this->author_config['id'],
                'headimgurl'  => isset($wxdata['headimgurl']) ? $wxdata['headimgurl'] : '',
                'nickname'  => isset($wxdata['nickname']) ? $wxdata['nickname'] : '微信用户',
                'sex'       => isset($wxdata['sex']) ? $wxdata['sex'] : 0,
                'subscribe' => isset($wxdata['subscribe']) ? $wxdata['subscribe'] : 0,
                'oauth'     => 'weixin',
                'subscribe_time'  => isset($wxdata['subscribe_time']) ? $wxdata['subscribe_time'] : time(),
                'token'     => md5(time().mt_rand(1,99999)),
                'password'  => '',
                'is_distribut' => 1,
            ];
            isset($wxdata['unionid']) && $user['unionid'] = $wxdata['unionid'];
            $ret = Db::name('users')->insert($user);
            if(!$ret){
                echo '失败';exit();
            }
        }
    }

/*  id,auid group_id name sort pid remark color
 * CREATE TABLE `think_user_group` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '分类ID',
  `auid` int(11) NOT NULL COMMENT '授权公众号id',
  `group_id` int(11) DEFAULT NULL COMMENT '标签id',
  `name` varchar(50) NOT NULL COMMENT '分类名称',
  `sort` smallint(5) unsigned NOT NULL DEFAULT '0' COMMENT '排序',
  `pid` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '上级分类ID',
  `create_time` datetime NOT NULL,
  `remark` varchar(255) DEFAULT NULL,
  `color` varchar(15) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=135 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='分类表';

 * */


    /**
     * 获取数据库粉丝列表
     */
    public function getFansDetailList($start_time = '',$end_time = '',$page = 1){
        $count = '';
        $where = [];
        if(!empty($start_time) && !empty($end_time)){
            $where = [
                'subscribe_time'=>['between',[$start_time,$end_time]],
            ];
        }
        $where['think_users.auid'] = ['eq',$this->author_config['id']];
        $count = Db::name('users')
                ->field('COUNT(*) total,COUNT(CASE WHEN subscribe = 1 THEN 1 ELSE NULL END) subscount,COUNT(CASE WHEN subscribe = 0 THEN 1 ELSE NULL END ) un_subscount,COUNT(CASE WHEN repeat_subscribe = 1 && subscribe = 1 THEN 1 ELSE NULL END) repeat_subscribe_count,COUNT(CASE WHEN is_second_unsubscribe = 1 THEN 1 ELSE NULL END) as second_unsubscribe_count')
                ->where($where)
                ->select();//关注人数
        $result = $this->users_model
                ->field('u.butt_id,u.sex,u.subscribe_time,u.unsubscribe_time,u.subscribe,u.openid,u.headimgurl,u.nickname,think_csuser.nickname as cs_nickname')
                ->alias('u')
                ->join('think_csuser','u.butt_id = think_csuser.id','left')
                ->where($where)
                ->order('subscribe_time desc')
                ->paginate(15,false,['page'=>$page]);

        foreach($result as $v){
            $map = [
                'openid' => ['eq',$v['openid']],
                'cs_id' => ['eq',$v['butt_id']]
            ];
            $v['chat_count'] = Db::connect('db_config_chatlog')->name('chatlog')->where($map)->group('send_type')->column('send_type,count(*) as chat_count');
        }

        //统计菜单栏点击数
        $click_count = Db::name('wechat_menu_click')->where('auid',$this->author_config['id'])->count();
        
        return json(['result'=>$result,'count'=>$count[0],'click_count' => $click_count]);
    }

    /**
     * 新建标签
     * @param type tag
     */
    public function addFansTag(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(isset($data['tag']) == false && empty($data['tag'])){
                return false;
            }
            $tag = $data['tag'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->createTag($tag);
    
            return json($result);
        }
    }

    /**
     * 获取公众号已创建的标签
     */
    public function getAllFansTag(){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getAllFanTags();
        return json($result);
    }

    /**
     * 编辑标签
     * @param type $id
     * @param type $tag
     */
    public function editFansTag(){
        if($this->request->isPost()){
            $data = $this->request->post();

            if(isset($data['id']) == false && isset($data['tag']) == false){
    
                return json(['msg'=>'参数错误']);
    
            }else if(empty($data['tag'])){
    
                return json(['msg'=>'标签不能为空']);
    
            }
    
            $id = $data['id'];
            $tag = $data['tag'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->updateTag($id,$tag);
            return json($result);
        }
    }

    /**
     * 删除标签
     * @param type $id
     * @return boolean
     */
    public function deleteFansTag(){
        if($this->request->isPost()){
            $data = $this->request->post();
            if(isset($data['id']) == false){
                return json(['msg'=>'参数错误']);
            }
            $id = $data['id'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->deleteTag($id);
            return json($result);
        }
    }

    /**
     * 获取标签下粉丝列表
     */
    public function getTagFansList($tagid,$next_openid = ''){
        $wechat_obj = $this->wechat_obj;
        $result = $wechat_obj->getTagUsersList($tagid,$next_openid);
        return json($result);
    }

    /**
     * 批量为用户打标签
     * @param array $openid_list
     * @param int $tagid
     * @return boolean
     */
    public function addsFansTags(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $openid_list = $data['openid_list'];
            $tagid = $data['tagid'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->batchUsersTag($tagid,$next_openid);
            return json($result);
        }
    }

    /**
     * 批量为用户取消标签
     * @param array $openid_list
     * @param int $tagid
     * @return boolean
     */
    public function deletesFansTags(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $openid_list = $data['openid_list'];
            $tagid = $data['tagid'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->batchCancelUsersTag($tagid,$next_openid);
            return json($result);
        }
    }

    /**
     * 获取用户身上的标签列表
     * @param type $openid
     * @return array
     */
    public function getFansTagsDetail(){
        if($this->request->isPost()){
            $data = $this->request->post();
            $openid = $data['openid'];
            $wechat_obj = $this->wechat_obj;
            $result = $wechat_obj->getUserTags($openid);
            return json($result);
        }
    }

    /**
     * 足迹
     */
    public function queryFootPrint($openid){
        $result = Db::name('footprint')->where('openid',$openid)->select();
        return json($result);
    }
// -----------------------------------------------  创建 ----------------------//
    public function partAuid(){
        // 根据用户users表auid创建不同的粉丝表
        $wechat_list = $this->author_wx_user_model->field('id')->select();
        $sql_list = [];

        foreach ($wechat_list as $wechat_id) {
//            var_dump($wechat_id);
//            var_dump($wechat_id['id']);
            $table_status = [];
            $table_status['id']=$wechat_id['id'];
            $table_name = 'think_users'.$wechat_id['id'];
            // 1 判断table是否存在
            $isTable = Db::query('SHOW TABLES LIKE "'.$table_name.'"');
            if($isTable){
                $table_status['has_table'] = 1;
            }else{
                $table_status['has_table'] = 0;
                // 1.1 创建table
                $sql_table = "CREATE TABLE  ".$table_name ;
                $sql = <<<sql
          (
  `user_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '表id',
  `auid` int(11) NOT NULL COMMENT '授权公众号id',
  `butt_id` int(10) unsigned DEFAULT NULL COMMENT '对接客服id',
  `nickname` varchar(50) DEFAULT NULL COMMENT '第三方返回昵称',
  `origin_qr` int(5) DEFAULT NULL COMMENT '来源二维码广告',
  `language` varchar(20) NOT NULL DEFAULT '' COMMENT '语言',
  `sex` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '0 保密 1 男 2 女',
  `tagid_list` varchar(255) DEFAULT 'a:0:{}' COMMENT '用户被打上的标签ID列表',
  `subscribe_scene` varchar(20) DEFAULT '' COMMENT '用户关注的渠道来源',
  `latitude` decimal(10,6) DEFAULT '0.000000' COMMENT '纬度',
  `longitude` decimal(10,6) DEFAULT '0.000000' COMMENT '经度',
  `precision` decimal(10,6) DEFAULT '0.000000' COMMENT '精度',
  `send_qrcode_time` bigint(16) DEFAULT NULL COMMENT '发送二维码时间',
  `oauth` varchar(10) DEFAULT '' COMMENT '第三方来源 wx weibo alipay',
  `openid` varchar(100) DEFAULT NULL COMMENT '第三方唯一标示',
  `headimgurl` varchar(255) DEFAULT NULL COMMENT '头像',
  `province` varchar(20) DEFAULT '' COMMENT '省份',
  `city` varchar(20) DEFAULT '' COMMENT '市区',
  `country` varchar(45) DEFAULT '0' COMMENT '县',
  `user_type` tinyint(1) DEFAULT NULL COMMENT '用户对话情况 0未对话 1初次对话 2二次对话',
  `is_second_unsubscribe` tinyint(1) DEFAULT '0' COMMENT '是否秒取关',
  `third_leader` int(11) DEFAULT '0' COMMENT '第三个上级',
  `token` varchar(64) DEFAULT '' COMMENT '用于app 授权类似于session_id',
  `create_butt_time` bigint(16) DEFAULT NULL COMMENT '创建对话时间',
  `last_butt_time` bigint(16) DEFAULT NULL COMMENT '最后对话时间',
  `subscribe` tinyint(1) NOT NULL COMMENT '是否关注 1关注 0取关',
  `subscribe_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '关注时间',
  `unsubscribe_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '取消关注时间',
  `repeat_subscribe` tinyint(1) DEFAULT '0' COMMENT '是否重复关注 1是 0否',
  `is_silent` tinyint(1) DEFAULT '0' COMMENT '0 静默 1 不静默',
  `is_talk` tinyint(1) DEFAULT '0' COMMENT '0未沟通 1已沟通',
  `groupid` tinyint(1) DEFAULT '0' COMMENT '用户所在的分组ID 0未沟通 1已沟通',
  `qr_scene` varchar(100) DEFAULT '' COMMENT '二维码扫码场景（开发者自定义）',
  `qr_scene_str` varchar(100) DEFAULT '' COMMENT '二维码扫码场景描述（开发者自定义）',
  `unionid` varchar(100) DEFAULT NULL,
  `mobile_validated` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '是否验证手机',
  `mobile` varchar(20) NOT NULL COMMENT '手机号码',
  `remark` varchar(100) DEFAULT '' COMMENT '备注',
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `openid` (`openid`) USING BTREE,
  KEY `auid` (`auid`)
) ENGINE=InnoDB AUTO_INCREMENT=8277 DEFAULT CHARSET=utf8;
sql;
                $table_status['sql'] = $sql_table;
                $sql_query = $sql_table.$sql ;
                $result = Db::query($sql_query);
                $table_status['create'] = $sql_query;
                $table_status['result'] = $result;
            }
            // 2 从总表获取数据
            $users_data = $this->users_model->where('auid',$wechat_id['id'])->select();
            if($users_data){
                //2.1 导入数据到子表
                $right_num = 0; $error_num = 0;
                $error_name = [];
                foreach ($users_data as $u_data) {
                    $sql_data=[
                        'user_id'=>$u_data['user_id'],
                        'auid'=>$u_data['auid'],
                        'butt_id'=>$u_data['butt_id'],
                        'nickname'=>$u_data['nickname'],
                        'origin_qr'=>$u_data['origin_qr'],
                        'language'=>$u_data['language'],
                        'sex'=>$u_data['sex'],
                        'tagid_list'=>$u_data['tagid_list'],
                        'subscribe_scene'=>$u_data['subscribe_scene'],
                        'latitude'=>$u_data['latitude'],
                        'longitude'=>$u_data['longitude'],
                        'precision'=>$u_data['precision'],
                        'send_qrcode_time'=>$u_data['send_qrcode_time'],
                        'oauth'=>$u_data['oauth'],
                        'openid'=>$u_data['openid'],
                        'headimgurl'=>$u_data['headimgurl'],
                        'province'=>$u_data['province'],
                        'city'=>$u_data['city'],
                        'country'=>$u_data['country'],
                        'user_type'=>$u_data['user_type'],
                        'is_second_unsubscribe'=>$u_data['is_second_unsubscribe'],
                        'third_leader'=>$u_data['third_leader'],
                        'token'=>$u_data['token'],
                        'create_butt_time'=>$u_data['create_butt_time'],
                        'last_butt_time'=>$u_data['last_butt_time'],
                        'subscribe'=>$u_data['subscribe'],
                        'subscribe_time'=>$u_data['subscribe_time'],
                        'unsubscribe_time'=>$u_data['unsubscribe_time'],
                        'repeat_subscribe'=>$u_data['repeat_subscribe'],
                        'is_silent'=>$u_data['is_silent'],
                        'is_talk'=>$u_data['is_talk'],
                        'groupid'=>$u_data['groupid'],
                        'qr_scene'=>$u_data['qr_scene'],
                        'qr_scene_str'=>$u_data['qr_scene_str'],
                        'unionid'=>$u_data['unionid'],
                        'mobile_validated'=>$u_data['mobile_validated'],
                        'mobile'=>$u_data['mobile'],
                        'remark'=>$u_data['remark'],
                    ];
                    $result = Db::table($table_name)->insert($sql_data);
                    if($result){
                        $right_num += 1;
                    }else{
                        $error_num += 1;
                        array_push($error_name,$sql_data['nickname']);
                    }
                }
                $table_status['process'] = [
                    'right' => $right_num,
                    'error' => $error_num,
                    'error_name' => $error_name
                ];
            }
            array_push($sql_list,$table_status);
        }
        return json([
            'list' => $wechat_list,
            'sql' => $sql_list
        ]);
    }

    /*
     * 导入数据到子表
     *  $sqlname = 'chatlog'.$butt_id % 10;
            $result = Db::connect('db_config_chatlog')->name($sqlname)->where('cs_id',$butt_id)->where('openid',$openid)->order('send_time asc')->select();
            $customerService = $this->csuser_model->where('id',$butt_id)->find();
     * */
    public function datato($wechat_id){
        // 2 从总表获取数据
        $users_data = $this->users_model->where('auid',$wechat_id)->select();
        if($users_data){
            //2.1 导入数据到子表
            $sqlname = 'think_users'.$wechat_id;
            $right_num = 0; $error_num = 0;
            foreach ($users_data as $u_data) {
                $sql_data=[
                    'user_id'=>$u_data['user_id'],
                    'auid'=>$u_data['auid'],
                    'butt_id'=>$u_data['butt_id'],
                    'nickname'=>$u_data['nickname'],
                    'origin_qr'=>$u_data['origin_qr'],
                    'language'=>$u_data['language'],
                    'sex'=>$u_data['sex'],
                    'tagid_list'=>$u_data['tagid_list'],
                    'subscribe_scene'=>$u_data['subscribe_scene'],
                    'latitude'=>$u_data['latitude'],
                    'longitude'=>$u_data['longitude'],
                    'precision'=>$u_data['precision'],
                    'send_qrcode_time'=>$u_data['send_qrcode_time'],
                    'oauth'=>$u_data['oauth'],
                    'openid'=>$u_data['openid'],
                    'headimgurl'=>$u_data['headimgurl'],
                    'province'=>$u_data['province'],
                    'city'=>$u_data['city'],
                    'country'=>$u_data['country'],
                    'user_type'=>$u_data['user_type'],
                    'is_second_unsubscribe'=>$u_data['is_second_unsubscribe'],
                    'third_leader'=>$u_data['third_leader'],
                    'token'=>$u_data['token'],
                    'create_butt_time'=>$u_data['create_butt_time'],
                    'last_butt_time'=>$u_data['last_butt_time'],
                    'subscribe'=>$u_data['subscribe'],
                    'subscribe_time'=>$u_data['subscribe_time'],
                    'unsubscribe_time'=>$u_data['unsubscribe_time'],
                    'repeat_subscribe'=>$u_data['repeat_subscribe'],
                    'is_silent'=>$u_data['is_silent'],
                    'is_talk'=>$u_data['is_talk'],
                    'groupid'=>$u_data['groupid'],
                    'qr_scene'=>$u_data['qr_scene'],
                    'qr_scene_str'=>$u_data['qr_scene_str'],
                    'unionid'=>$u_data['unionid'],
                    'mobile_validated'=>$u_data['mobile_validated'],
                    'mobile'=>$u_data['mobile'],
                    'remark'=>$u_data['remark'],
                ];
                $result = Db::table($sqlname)->insert($sql_data); // 这样一一对应可以插入数据
//              $result = Db::table($sqlname)->insert($u_data); // $u_data 是对象,需要转一次才能插入,转入失败了
                if($result){
                    $right_num += 1;
                }else{
                    $error_num += 1;
                }
            }
            return json([
                'right' => $right_num,
                'error' => $error_num
            ]);
        }
    }

    /*
     * 写入数据到新数据
     * */


    public function create_table(){
        $create_table = <<<sql
       CREATE TABLE `think_users1`    (
  `user_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '表id',
  `auid` int(11) NOT NULL COMMENT '授权公众号id',
  `butt_id` int(10) unsigned DEFAULT NULL COMMENT '对接客服id',
  `nickname` varchar(50) DEFAULT NULL COMMENT '第三方返回昵称',
  `origin_qr` int(5) DEFAULT NULL COMMENT '来源二维码广告',
  `language` varchar(20) NOT NULL DEFAULT '' COMMENT '语言',
  `sex` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '0 保密 1 男 2 女',
  `tagid_list` varchar(255) DEFAULT 'a:0:{}' COMMENT '用户被打上的标签ID列表',
  `subscribe_scene` varchar(20) DEFAULT '' COMMENT '用户关注的渠道来源',
  `latitude` decimal(10,6) DEFAULT '0.000000' COMMENT '纬度',
  `longitude` decimal(10,6) DEFAULT '0.000000' COMMENT '经度',
  `precision` decimal(10,6) DEFAULT '0.000000' COMMENT '精度',
  `send_qrcode_time` bigint(16) DEFAULT NULL COMMENT '发送二维码时间',
  `oauth` varchar(10) DEFAULT '' COMMENT '第三方来源 wx weibo alipay',
  `openid` varchar(100) DEFAULT NULL COMMENT '第三方唯一标示',
  `headimgurl` varchar(255) DEFAULT NULL COMMENT '头像',
  `province` varchar(20) DEFAULT '' COMMENT '省份',
  `city` varchar(20) DEFAULT '' COMMENT '市区',
  `country` varchar(45) DEFAULT '0' COMMENT '县',
  `user_type` tinyint(1) DEFAULT NULL COMMENT '用户对话情况 0未对话 1初次对话 2二次对话',
  `is_second_unsubscribe` tinyint(1) DEFAULT '0' COMMENT '是否秒取关',
  `third_leader` int(11) DEFAULT '0' COMMENT '第三个上级',
  `token` varchar(64) DEFAULT '' COMMENT '用于app 授权类似于session_id',
  `create_butt_time` bigint(16) DEFAULT NULL COMMENT '创建对话时间',
  `last_butt_time` bigint(16) DEFAULT NULL COMMENT '最后对话时间',
  `subscribe` tinyint(1) NOT NULL COMMENT '是否关注 1关注 0取关',
  `subscribe_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '关注时间',
  `unsubscribe_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '取消关注时间',
  `repeat_subscribe` tinyint(1) DEFAULT '0' COMMENT '是否重复关注 1是 0否',
  `is_silent` tinyint(1) DEFAULT '0' COMMENT '0 静默 1 不静默',
  `is_talk` tinyint(1) DEFAULT '0' COMMENT '0未沟通 1已沟通',
  `groupid` tinyint(1) DEFAULT '0' COMMENT '用户所在的分组ID 0未沟通 1已沟通',
  `qr_scene` varchar(100) DEFAULT '' COMMENT '二维码扫码场景（开发者自定义）',
  `qr_scene_str` varchar(100) DEFAULT '' COMMENT '二维码扫码场景描述（开发者自定义）',
  `unionid` varchar(100) DEFAULT NULL,
  `mobile_validated` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '是否验证手机',
  `mobile` varchar(20) NOT NULL COMMENT '手机号码',
  `remark` varchar(100) DEFAULT '' COMMENT '备注',
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `openid` (`openid`) USING BTREE,
  KEY `auid` (`auid`)
) ENGINE=InnoDB AUTO_INCREMENT=8277 DEFAULT CHARSET=utf8;
sql;
        $reslut = Db::query($create_table);
        var_dump($reslut);
    }

    public function checktable(){
        $isTable = Db::query('SHOW TABLES LIKE "think_users1"');
        if($isTable){
            echo '表存在';
        }else{
            echo '表不存在';
        }
    }

    public function partWxUser(){
        // 根据用户users表auid创建不同的粉丝表
        $wechat_list = $this->author_wx_user_model->select();
        var_dump($wechat_list);
    }



    /*
     * 粉丝用户分表存放
     * */
    public function partUsers(){
        // 根据用户users表auid创建不同的粉丝表
        $wechat_list = $this->author_wx_user_model->field('id')->select();
        $sql_list = [];
        foreach ($wechat_list as $wechat_id) {
            $sql_table = "CREATE TABLE `think_users".$wechat_id['id']."`";

            $sql = <<<sql
          (
  `user_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT '表id',
  `auid` int(11) NOT NULL COMMENT '授权公众号id',
  `butt_id` int(10) unsigned DEFAULT NULL COMMENT '对接客服id',
  `nickname` varchar(50) DEFAULT NULL COMMENT '第三方返回昵称',
  `origin_qr` int(5) DEFAULT NULL COMMENT '来源二维码广告',
  `language` varchar(20) NOT NULL DEFAULT '' COMMENT '语言',
  `sex` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '0 保密 1 男 2 女',
  `tagid_list` varchar(255) DEFAULT 'a:0:{}' COMMENT '用户被打上的标签ID列表',
  `subscribe_scene` varchar(20) DEFAULT '' COMMENT '用户关注的渠道来源',
  `latitude` decimal(10,6) DEFAULT '0.000000' COMMENT '纬度',
  `longitude` decimal(10,6) DEFAULT '0.000000' COMMENT '经度',
  `precision` decimal(10,6) DEFAULT '0.000000' COMMENT '精度',
  `send_qrcode_time` bigint(16) DEFAULT NULL COMMENT '发送二维码时间',
  `oauth` varchar(10) DEFAULT '' COMMENT '第三方来源 wx weibo alipay',
  `openid` varchar(100) DEFAULT NULL COMMENT '第三方唯一标示',
  `headimgurl` varchar(255) DEFAULT NULL COMMENT '头像',
  `province` varchar(20) DEFAULT '' COMMENT '省份',
  `city` varchar(20) DEFAULT '' COMMENT '市区',
  `country` varchar(45) DEFAULT '0' COMMENT '县',
  `user_type` tinyint(1) DEFAULT NULL COMMENT '用户对话情况 0未对话 1初次对话 2二次对话',
  `is_second_unsubscribe` tinyint(1) DEFAULT '0' COMMENT '是否秒取关',
  `third_leader` int(11) DEFAULT '0' COMMENT '第三个上级',
  `token` varchar(64) DEFAULT '' COMMENT '用于app 授权类似于session_id',
  `create_butt_time` bigint(16) DEFAULT NULL COMMENT '创建对话时间',
  `last_butt_time` bigint(16) DEFAULT NULL COMMENT '最后对话时间',
  `subscribe` tinyint(1) NOT NULL COMMENT '是否关注 1关注 0取关',
  `subscribe_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '关注时间',
  `unsubscribe_time` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '取消关注时间',
  `repeat_subscribe` tinyint(1) DEFAULT '0' COMMENT '是否重复关注 1是 0否',
  `is_silent` tinyint(1) DEFAULT '0' COMMENT '0 静默 1 不静默',
  `is_talk` tinyint(1) DEFAULT '0' COMMENT '0未沟通 1已沟通',
  `groupid` tinyint(1) DEFAULT '0' COMMENT '用户所在的分组ID 0未沟通 1已沟通',
  `qr_scene` varchar(100) DEFAULT '' COMMENT '二维码扫码场景（开发者自定义）',
  `qr_scene_str` varchar(100) DEFAULT '' COMMENT '二维码扫码场景描述（开发者自定义）',
  `unionid` varchar(100) DEFAULT NULL,
  `mobile_validated` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT '是否验证手机',
  `mobile` varchar(20) NOT NULL COMMENT '手机号码',
  `remark` varchar(100) DEFAULT '' COMMENT '备注',
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `openid` (`openid`) USING BTREE,
  KEY `auid` (`auid`)
) ENGINE=InnoDB AUTO_INCREMENT=8277 DEFAULT CHARSET=utf8;
sql;
            var_dump($sql_table);

            array_push($sql_list,$sql_table);
        }
        var_dump($sql_list);

        return json($wechat_list);


    }




}